package auth

import (
	"github.com/gin-gonic/gin"
	"wskyygyso/api/app/http/controllers/api/v1"
	"wskyygyso/api/app/models/user"
	"wskyygyso/api/app/requests"
	"wskyygyso/api/pkg/jwt"
	"wskyygyso/api/pkg/response"
)

type SignUpController struct {
	v1.BaseApiController
}

func (s *SignUpController) IsPhoneExist(c *gin.Context) {
	request := requests.SignupPhoneExistRequest{}
	if ok := requests.Validate(c, &request, requests.ValidateSignupPhoneExistRequest); !ok {
		return
	}

	response.JSON(c, gin.H{
		"exists": user.IsPhoneExists(request.Phone),
	})
}

func (s *SignUpController) IsEmailExist(c *gin.Context) {
	request := requests.SignupEmailExistRequest{}
	if ok := requests.Validate(c, &request, requests.ValidateSignupEmailExistRequest); !ok {
		return
	}
	response.JSON(c, gin.H{
		"exist": user.IsEmailExists(request.Email),
	})
}

func (s *SignUpController) SignupUsingPhone(c *gin.Context) {
	request := requests.SignupUsingPhoneRequest{}
	if ok := requests.Validate(c, &request, requests.SignupUsingPhone); !ok {
		return
	}
	_user := user.User{
		Phone:    request.Phone,
		PassWord: request.PassWord,
		Name:     request.Name,
	}
	_user.Create()
	if _user.ID > 0 {
		token := jwt.NewJwt().IssueToken(_user.GetStringId(), _user.Name)
		response.CreatedJSON(c, gin.H{
			"token": token,
			"data":  _user,
		})
	} else {
		response.Abort500(c, "创建用户失败，请稍后尝试~")
	}
}

func (s *SignUpController) SignupUsingEmail(c *gin.Context) {
	request := requests.SignupUsingEmailRequest{}
	if ok := requests.Validate(c, &request, requests.SignupUsingEmail); !ok {
		return
	}
	_user := user.User{
		Email:    request.Email,
		PassWord: request.PassWord,
		Name:     request.Name,
	}
	_user.Create()
	if _user.ID > 0 {
		token := jwt.NewJwt().IssueToken(_user.GetStringId(), _user.Name)
		response.CreatedJSON(c, gin.H{
			"token": token,
			"data":  _user,
		})
	} else {
		response.Abort500(c, "创建用户失败，请稍后尝试~")
	}
}
